package com.it.emall.controller;

import com.github.pagehelper.PageHelper;
import com.it.emall.domain.Ingredients;
import com.it.emall.domain.Recipes;
import com.it.emall.mapper.RecipeMapper;
import com.it.emall.service.RecipesService;
import com.it.emall.utils.JwtHelper;
import com.it.emall.utils.ResponseUtils;
import com.it.emall.vo.RecipeRequest;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wx/recipes")
public class RecipesController {

    @Autowired
    private RecipesService recipesService;

    @GetMapping("/list")
    public Object list(@RequestParam(value = "page",required = false,defaultValue = "1") Integer page,
                       @RequestParam(value = "limit",required = false,defaultValue = "10") Integer limit){


        PageHelper.startPage(page,limit);
        List<Recipes> recipes = recipesService.selectIngredientsList();
        Map<String,Object> data = new HashMap<>();
        data.put("list",recipes);
        return ResponseUtils.ok(data);

    }

    /**
     * 模糊查询食谱
     * @param search 搜索关键字
     * @return 符合条件的食谱列表
     */
    @GetMapping("/search")
    public Object searchRecipes(@RequestParam String search) {
        // 调用 Service 层的模糊查询方法
        List<Recipes> recipesList = recipesService.searchRecipesByKeyword(search);
        return ResponseUtils.ok(recipesList);  // 返回查询结果
    }

    @GetMapping("/id")
    public Object selectRecipesById(@RequestParam Integer id){
        Recipes recipes = recipesService.selectRecipesById(id);
        return ResponseUtils.ok(recipes);

    }

    @GetMapping("/ingredientsid")
    public Object selectRecipesByIngredientId(@RequestParam Integer ingredientId){
        Recipes recipes = recipesService.selectRecipesByIngredientId(ingredientId);
        return ResponseUtils.ok(recipes);
    }

    //增加食谱
    @PostMapping("/add")
    public Object addRecipes(@RequestBody RecipeRequest request){
        Map<String, Object> response = new HashMap<>();
        try {
            // 解析前端 JSON 数据
            // 直接使用 request 对象获取参数
            String recipeName = request.getRecipeName();

            String ingredientName = request.getIngredientName();
            String ingredientDesc = request.getIngredientDesc();
            String picUrl = request.getPicUrl();
            String iconUrl = request.getIconUrl();
            int l1CategoryId = request.getL1CategoryId();

            Recipes recipe = new Recipes();
            recipe.setRecipeName(recipeName);
            recipe.setCategory(ingredientName);
            recipe.setDescription(request.getDescription());
            recipe.setInstructions(request.getInstructions());
            recipe.setCalories(request.getCalories());
            recipe.setProtein(request.getProtein());
            recipe.setFat(request.getFat());
            recipe.setCarbohydrate(request.getCarbohydrate());
            recipe.setImageUrl(request.getImageUrl());
            recipe.setUserId(request.getUserId());

            // 添加食谱
            if (recipesService.addRecipe(recipe, ingredientName, ingredientDesc, picUrl, iconUrl, l1CategoryId) > 0) {
                response.put("status", "success");
                response.put("message", "食谱上传成功");
            } else {
                response.put("status", "error");
                response.put("message", "食谱上传失败");
            }
        } catch (Exception e) {
            response.put("status", "error");
            response.put("message", "参数错误：" + e.getMessage());
        }
        return response;
    }


    /**
     * 更新食谱并同步更新食材表中的pid和name
     *
     * @param recipe 新的食谱信息
     * @param pid 旧的分类ID
     * @return 更新结果
     */
    @PostMapping("/update")
    public Object updateRecipe(@RequestBody Recipes recipe, @RequestParam Integer pid) {
        int result = recipesService.updateRecipeAndSyncCategory(recipe, pid);
        if (result > 0) {
            return ResponseEntity.ok("食谱更新成功并同步分类更新");
        } else {
            return ResponseUtils.fail(500,"食谱更新失败");
        }
    }

    // 删除食谱
    @GetMapping("/delete")
    public Object deleteRecipe(@RequestParam Integer id, @RequestParam int userId) {
        int result = recipesService.deleteRecipeById(id, userId);
        return ResponseUtils.ok(result);
    }
    // 根据用户ID查询该用户发布的食谱
    @GetMapping("/userrecipes")
    public Object getUserRecipes(@RequestParam int userId) {
        List<Recipes> recipes = recipesService.selectRecipesByuserId(userId);
        return ResponseUtils.ok(recipes);

    }

    //查询用户发布食谱的详情页 用于修改食谱
    @GetMapping("/selectupdate")
    public Object getselectRecipesByuserIdRecipe(@RequestParam Integer id,@RequestHeader("token") String token){
        Integer userId = JwtHelper.verifyTokenAndGetUserId(token);

        if (userId == null) {
            return ResponseUtils.fail(500,"请登入");
        }
        Recipes recipes = recipesService.selectRecipesByuserIdRecipe(id, userId);
        return ResponseUtils.ok(recipes);
    }
}
